from django.shortcuts import render, redirect

from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import UserModelForm


def user_list(request):
    # 1. 获取所有用户信息
    user_list = models.UserInfo.objects.all()
    # for user in user_list:
    #     print(user.id, user.name, user.password, user.age, user.account, user.create_time.strftime('%Y-%m-%d'),
    #           # %H:%M:%S
    #           user.get_gender_display(), user.depart.title)  # 根据id自动去关联表的depart对象中查找对应的title
    page_obj = Pagination(request, user_list, page_size=2)
    context = {
        'user_list': page_obj.page_queryset,
        'page_str': page_obj.html(),
    }
    return render(request, 'user_list.html', context)


def user_model_form_add(request):
    # 添加用户
    if request.method == 'GET':
        form_obj = UserModelForm()
        return render(request, 'user_model_form_add.html', {'form_obj': form_obj})

    form_obj = UserModelForm(request.POST)
    if form_obj.is_valid():
        form_obj.save()
        return redirect('/user/list')

    return render(request, 'user_model_form_add.html', {'form_obj': form_obj})


def user_delete(request, nid):
    # # 1. 获取用户提交的数据
    # user_id = request.GET.get('nid')
    # 2. 将数据写入到数据库
    models.UserInfo.objects.filter(id=nid).delete()
    # 3. 跳转到部门列表页面
    return redirect('/user/list')


def user_edit(request, nid):
    # 根据ID去数据库获取当前编辑的用户信息(一行数据，对象)
    row_obj = models.UserInfo.objects.filter(id=nid).first()
    if request.method == 'GET':
        # 根据nid获取当前编辑的用户信息
        form = UserModelForm(instance=row_obj)
        return render(request, 'user_edit.html', {'form': form})

    # 将修改后的数据写入到数据库
    form = UserModelForm(data=request.POST, instance=row_obj)
    if form.is_valid():
        form.save()  # 默认保存的是用户输入的所有数据
        # 在用户输入的以外增加值
        # form.instance.create_time = '2019-01-01'
        return redirect('/user/list')

    return render(request, 'user_edit.html', {'form': form})